<template>
  <el-dialog :title="title" :visible.sync="openDistribution" width="500px" append-to-body>
    <el-form class="dialog-form" label-suffix="：" ref="form" :model="form" :rules="rules" label-width="120px"
             :style="{'--form-item-width': '100%'}"
    >
      <el-form-item label="分配类型" prop="type">
        <el-select v-model="form.type" placeholder="分配类型" clearable size="small" @change="triggerDisCustomer">
          <el-option
            v-for="dict in allotTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分配用户" prop="userId" v-if="customerUserAllot">
        <el-select v-model="form.userIds" placeholder="选择用户信息"
                   multiple filterable
                   clearable size="small">
          <el-option
            v-for="dict in this.userList"
            :key="dict.userId"
            :label="dict.nickName + '（' + dict.deptName + '）'"
            :value="dict.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分配部门" prop="deptId" v-if="customerDeptAllot">
        <el-select v-model="form.deptIds" placeholder="选择部门信息"
                   multiple filterable
                   clearable size="small">
          <el-option
            v-for="dict in this.deptList"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">取 消</el-button>
      <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {allotCustomerToUser, allotCustomerToDept} from "@/api/customerPool/customerPool";

import {oneKeyIssueToDept, oneKeyIssueToUser} from "@/api/customer/totalCustomer";

import {oneKeyIssueToDeptExport, oneKeyIssueToUserExport} from "@/api/exportLog/index";

import {teamCustomerTransferToUser, teamCustomerTransferToDept} from "@/api/teamCustomer/teamCustomer";

import { getUserList, getDeptList} from "@/api/customerPool/customerPool"

export default {
  name: 'BathDisCustomer',
  data() {
    return {
      loading: false,
      allotTypeList: [
        {value: 1, label: "下级客户池"},
        {value: 2, label: "指定客户"}
      ],
      ids: [],
      // 弹出层标题
      title: '分配客户',
      // 是否显示弹出层
      openDistribution: false,
      customerUserAllot: false,
      customerDeptAllot: false,
      type: "",
      // 表单参数
      form: {
        type: undefined,
        userIds: [],
        deptIds: []
      },
      userList: [],
      deptList:[],

      operationType: '',

      // 表单校验
      rules: {
        type: [
          {required: true, message: '分配类型不能为空', trigger: 'change'}
        ],
        userIds: [
          {required: true, message: '用户不能为空', trigger: 'change'}
        ],
        deptIds: [
          {required: true, message: '部门不能为空', trigger: 'change'}
        ],
      }
    }
  },
  methods: {
    /** 触发分配人员 */
    triggerDisCustomer() {
      const type = this.form.type;
      // 分配客户
      if (type == 2) {
        this.customerUserAllot = true;
        this.customerDeptAllot = false
      } else {
        this.customerUserAllot = false;
        this.customerDeptAllot = true;
      }
      this.form.deptIds = [];
      this.form.userIds = [];
    },

    /** 获取用户信息 */
    getUserInfoList() {
      const query = {
        type: "1"
      }
      getUserList(query).then(response => {
        this.userList = response.data;
      })
    },
    getDeptInfoList(val) {
      const query = {
        type: val === 'teamCustomer' ? "2" : "1"
      }
      getDeptList(query).then(response => {
        this.deptList = response.data;
      })
    },

    /** 打开弹窗 */
    openDialog(ids, operationType) {
      this.ids = ids;
      this.operationType = operationType;
      this.getUserInfoList();
      this.getDeptInfoList(operationType);
      this.openDistribution = true
      this.customerUserAllot = false;
      this.customerDeptAllot = false
      this.resetForm('form')
    },
    /** 取消按钮 */
    cancel() {
      this.openDistribution = false
      // 添加刷新列表
     //if (this.$parent.getList) {
     //  this.$parent.getList();
     //}
     //// 星级弹框二次弹框刷新上一个弹框
     //if (this.$parent.$parent.refreshList) {
     //  console.log("二级弹框取消getList刷新了")
     //  this.$parent.$parent.refreshList();
     //}
    },
    /** 确定按钮 */
    submitForm() {
      this.type = this.form.type;
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$modal.loading("正在加载处理数据，请稍候！");
          const deptsEnd = [];
          const deptIds = this.form.deptIds;
          deptIds.forEach(item => {
            const obj = this.deptList.find(it => it.deptId == item);
            deptsEnd.push(obj);
          })
          // 分配给部门
          if (this.type == "1") {
            //  客户池分配
            if (this.operationType == 'poolCustomer') {
              const data = {
                disCustomerBos: this.ids,
                deptBos: deptsEnd
              }
              allotCustomerToDept(data).then(resp => {
                this.$modal.msgSuccess("分配成功");
                this.$modal.closeLoading();
                this.openDistribution = false
                if (this.$parent.getList) {
                  this.$parent.getList();
                }
              }).finally(() => {
                this.$modal.closeLoading();
                this.openDistribution = false
              });
              // 一键下发
            } else if (this.operationType == 'totalCustomer') {
              const data = {
                disCustomerBos: this.ids,
                deptBos: deptsEnd
              }
              oneKeyIssueToDept(data).then(resp => {
                this.$modal.msgSuccess("分配成功");
                this.$modal.closeLoading();
                this.openDistribution = false
                if (this.$parent.getList) {
                  this.$parent.getList();
                }
              }).finally(() => {
                this.$modal.closeLoading();
                this.openDistribution = false
              });
              // 导入一键下发
            } else if (this.operationType == 'exportInfo') {
              const data = {
                logsInfos: this.ids,
                deptBos: deptsEnd
              }
              oneKeyIssueToDeptExport(data).then(resp => {
                this.$modal.msgSuccess("分配成功");
                this.$modal.closeLoading();
                this.openDistribution = false
                if (this.$parent.getList) {
                  this.$parent.getList();
                }
              }).finally(() => {
                this.$modal.closeLoading();
                this.openDistribution = false
              });
            } else if (this.operationType == 'teamCustomer') {
              const data = {
                disCustomerBos: this.ids,
                deptBos: deptsEnd
              }
              teamCustomerTransferToDept(data).then(resp => {
                this.$modal.msgSuccess("转移成功");
                this.$modal.closeLoading();
                this.openDistribution = false
                if (this.$parent.getList) {
                  this.$parent.getList();
                }
                // 星级弹框二次弹框刷新上一个弹框
                if (this.$parent.$parent.refreshList) {
                  console.log("二级弹框取消getList刷新了")
                  this.$parent.$parent.refreshList();
                }
              }).finally(() => {
                this.$modal.closeLoading();
                this.openDistribution = false
              });
            }
          } else {
            const usersEnd = [];
            const userIds = this.form.userIds;
            userIds.forEach(item => {
              const obj = this.userList.find(it => it.userId == item);
              const data = {
                userId: obj.userId,
                userDeptId: obj.deptId,
                nickName: obj.nickName
              }
              usersEnd.push(data);
            })
            // 客户池分配到用户
            if (this.operationType == 'poolCustomer') {
              const data = {
                disCustomerBos: this.ids,
                userBos: usersEnd
              }
              allotCustomerToUser(data).then(resp => {
                this.$modal.msgSuccess("分配成功");
                this.$modal.closeLoading();
                this.openDistribution = false
                if (this.$parent.getList) {
                  this.$parent.getList();
                }
              }).finally(() => {
                this.$modal.closeLoading();
                this.openDistribution = false
              });
              // 总客户一键下发分配到用户
            } else if (this.operationType == 'totalCustomer') {
              const data = {
                disCustomerBos: this.ids,
                userBos: usersEnd
              }
              oneKeyIssueToUser(data).then(resp => {
                this.$modal.msgSuccess("分配成功");
                this.$modal.closeLoading();
                this.openDistribution = false
                if (this.$parent.getList) {
                  this.$parent.getList();
                }
              }).finally(() => {
                this.$modal.closeLoading();
                this.openDistribution = false
              });
              // 导入一键下发分配到用户
            } else if (this.operationType == 'exportInfo') {
              const data = {
                logsInfos: this.ids,
                userBos: usersEnd
              }
              oneKeyIssueToUserExport(data).then(resp => {
                this.$modal.msgSuccess("分配成功");
                this.$modal.closeLoading();
                this.openDistribution = false
                if (this.$parent.getList) {
                  this.$parent.getList();
                }
              }).finally(() => {
                this.$modal.closeLoading();
                this.openDistribution = false
              });
              // 团队客户分配到用户
            } else if (this.operationType == 'teamCustomer') {
              const data = {
                disCustomerBos: this.ids,
                userBos: usersEnd
              }
              teamCustomerTransferToUser(data).then(resp => {
                this.$modal.msgSuccess("转移成功");
                this.$modal.closeLoading();
                this.openDistribution = false
                if (this.$parent.getList) {
                  this.$parent.getList();
                }
                // 星级弹框二次弹框刷新上一个弹框
                if (this.$parent.$parent.refreshList) {
                  console.log("二级弹框取消getList刷新了")
                  this.$parent.$parent.refreshList();
                }
              }).finally(() => {
                this.$modal.closeLoading();
                this.openDistribution = false
              });
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
